from typing import Optional, Any, Dict, List
from pydantic import BaseModel, Field
from datetime import datetime
from app.shared.constants.status_codes import BusinessCode


class BaseResponse(BaseModel):
    """基础响应模型"""
    success: bool = Field(description="操作是否成功")
    code: int = Field(description="状态码")
    message: str = Field(description="响应消息")
    data: Optional[Any] = Field(default=None, description="响应数据")
    timestamp: datetime = Field(default_factory=datetime.utcnow, description="时间戳")
    request_id: Optional[str] = Field(default=None, description="请求ID")


class SuccessResponse(BaseResponse):
    """成功响应模型"""
    success: bool = True
    code: int = BusinessCode.SUCCESS


class ErrorResponse(BaseResponse):
    """错误响应模型"""
    success: bool = False
    errors: Optional[List[Dict[str, str]]] = Field(default=None, description="错误详情")


class PaginationMeta(BaseModel):
    """分页元数据"""
    total: int = Field(description="总数量")
    page: int = Field(description="当前页码")
    page_size: int = Field(description="每页数量")
    total_pages: int = Field(description="总页数")
    has_next: bool = Field(description="是否有下一页")
    has_prev: bool = Field(description="是否有上一页")


class PaginatedResponse(SuccessResponse):
    """分页响应模型"""
    data: Dict[str, Any] = Field(description="分页数据")
    
    class Config:
        schema_extra = {
            "example": {
                "success": True,
                "code": 10000,
                "message": "查询成功",
                "data": {
                    "items": [],
                    "total": 100,
                    "page": 1,
                    "page_size": 20,
                    "total_pages": 5,
                    "has_next": True,
                    "has_prev": False
                },
                "timestamp": "2024-01-01T12:00:00Z",
                "request_id": "req_12345"
            }
        }


class ValidationError(BaseModel):
    """验证错误模型"""
    field: str = Field(description="字段名")
    message: str = Field(description="错误消息")
    value: Optional[Any] = Field(default=None, description="错误值")


class TokenResponse(BaseModel):
    """令牌响应模型"""
    access_token: str = Field(description="访问令牌")
    refresh_token: str = Field(description="刷新令牌")
    token_type: str = Field(default="bearer", description="令牌类型")
    expires_in: int = Field(description="过期时间(秒)")


class UserInfo(BaseModel):
    """用户信息模型"""
    id: int = Field(description="用户ID")
    username: str = Field(description="用户名")
    full_name: Optional[str] = Field(default=None, description="全名")
    email: Optional[str] = Field(default=None, description="邮箱")
    phone: Optional[str] = Field(default=None, description="手机号")
    role: str = Field(description="用户角色")
    avatar_url: Optional[str] = Field(default=None, description="头像URL")
    is_active: bool = Field(description="是否激活")
    last_login_at: Optional[datetime] = Field(default=None, description="最后登录时间")
    created_at: datetime = Field(description="创建时间")


class DeviceInfo(BaseModel):
    """设备信息模型"""
    id: int = Field(description="设备ID")
    device_code: str = Field(description="设备编码")
    device_name: str = Field(description="设备名称")
    device_type: str = Field(description="设备类型")
    location_name: Optional[str] = Field(default=None, description="位置名称")
    latitude: Optional[float] = Field(default=None, description="纬度")
    longitude: Optional[float] = Field(default=None, description="经度")
    status: str = Field(description="设备状态")
    materials_level: Optional[int] = Field(default=None, description="耗材余量")
    last_maintenance_at: Optional[datetime] = Field(default=None, description="最后维护时间")
    next_maintenance_at: Optional[datetime] = Field(default=None, description="下次维护时间")
    created_at: datetime = Field(description="创建时间")


class WorkOrderInfo(BaseModel):
    """工单信息模型"""
    id: int = Field(description="工单ID")
    order_number: str = Field(description="工单号")
    device_id: int = Field(description="设备ID")
    device_name: Optional[str] = Field(default=None, description="设备名称")
    creator_id: int = Field(description="创建者ID")
    creator_name: Optional[str] = Field(default=None, description="创建者姓名")
    assignee_id: Optional[int] = Field(default=None, description="负责人ID")
    assignee_name: Optional[str] = Field(default=None, description="负责人姓名")
    title: str = Field(description="工单标题")
    description: Optional[str] = Field(default=None, description="工单描述")
    priority: str = Field(description="优先级")
    status: str = Field(description="工单状态")
    work_type: str = Field(description="工单类型")
    scheduled_at: Optional[datetime] = Field(default=None, description="计划时间")
    started_at: Optional[datetime] = Field(default=None, description="开始时间")
    completed_at: Optional[datetime] = Field(default=None, description="完成时间")
    created_at: datetime = Field(description="创建时间")


class AlertInfo(BaseModel):
    """告警信息模型"""
    id: int = Field(description="告警ID")
    device_id: int = Field(description="设备ID")
    device_name: Optional[str] = Field(default=None, description="设备名称")
    alert_type: str = Field(description="告警类型")
    level: str = Field(description="告警级别")
    title: str = Field(description="告警标题")
    message: Optional[str] = Field(default=None, description="告警消息")
    is_resolved: bool = Field(description="是否已解决")
    resolved_by: Optional[int] = Field(default=None, description="解决人ID")
    resolved_at: Optional[datetime] = Field(default=None, description="解决时间")
    created_at: datetime = Field(description="创建时间")


# 响应构造函数
def success_response(
    data: Any = None,
    message: str = "操作成功",
    code: int = BusinessCode.SUCCESS,
    request_id: str = None
) -> Dict[str, Any]:
    """构造成功响应"""
    return {
        "success": True,
        "code": code,
        "message": message,
        "data": data,
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "request_id": request_id
    }


def error_response(
    message: str = "操作失败",
    code: int = BusinessCode.OPERATION_FAILED,
    errors: List[Dict[str, str]] = None,
    request_id: str = None
) -> Dict[str, Any]:
    """构造错误响应"""
    return {
        "success": False,
        "code": code,
        "message": message,
        "errors": errors,
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "request_id": request_id
    }


def paginated_response(
    items: List[Any],
    total: int,
    page: int,
    page_size: int,
    message: str = "查询成功",
    request_id: str = None
) -> Dict[str, Any]:
    """构造分页响应"""
    total_pages = (total + page_size - 1) // page_size
    
    return success_response(
        data={
            "items": items,
            "total": total,
            "page": page,
            "page_size": page_size,
            "total_pages": total_pages,
            "has_next": page < total_pages,
            "has_prev": page > 1
        },
        message=message,
        request_id=request_id
    )